package com.raising.modules.sys.service;

import com.raising.framework.service.CrudService;
import com.raising.modules.sys.dao.DictDao;
import com.raising.modules.sys.dao.DictItemDao;
import com.raising.modules.sys.entity.Dict;
import com.raising.modules.sys.entity.DictItem;
import com.raising.utils.JStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
* 字典表 Service层
* @author gaoy
* @version 1.0
*/
@Service
@Transactional(rollbackFor = Exception.class)
public class DictService extends CrudService<DictDao, Dict> {
	@Autowired
	private DictItemDao dictItemDao;
	/**
	 * 保存字典表与明细表
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public int saveDictAndItems(Dict dict){
		List<DictItem> items = dict.getDictItemList();
		if(dict.getIsNewId()){
			//新建
			dict.setStatus("1");
			dict.preInsert(null);
			dao.insert(dict);
		} else {
			//编辑
			DictItem itemDel = new DictItem();
			itemDel.setDictId(dict.getId());
			dictItemDao.delete(itemDel);
			dict.preUpdate(null);
			dao.update(dict);
		}
		for(DictItem item:items){
			if(JStringUtils.isNotBlank(item.getValue())
					&& JStringUtils.isNotBlank(item.getLabel())){
				item.setDictId(dict.getId());
				item.setDictValue(dict.getValue());
				item.setStatus("1");
				item.preInsert(null);
				dictItemDao.insert(item);
			}
		}
		return 1;
	}
	
	
	/**
	 * 删除数据-字典主表与从表【重写】 
	 * @author GY
	 */
	@Override
    @Transactional(rollbackFor = Exception.class)
    public int delete(String id) {
    	DictItem itemDel = new DictItem();
		itemDel.setDictId(id);
    	dictItemDao.delete(itemDel);
        return dao.delete(id);
    }
}
